package com.jkdl.springboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.jkdl.springboot.common.util.JsonResult;
import com.jkdl.springboot.common.util.Md5Util;
import com.jkdl.springboot.common.util.WxUtil.HttpUtil;
import com.jkdl.springboot.common.util.WxUtil.WxConfigUtil;
import com.jkdl.springboot.dao.UCompanyUserMapper;
import com.jkdl.springboot.domain.*;
import com.jkdl.springboot.entity.UCompanyUser;
import com.jkdl.springboot.exception.BusinessException;
import com.jkdl.springboot.service.SystemUserRoleAuthService;
import com.jkdl.springboot.service.UCompanyUserService;
import com.vdurmont.emoji.EmojiParser;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

@Slf4j
@Service
public class UCompanyUserServiceImpl implements UCompanyUserService {

    @Autowired
    private UCompanyUserMapper uCompanyUserMapper;

    @Autowired
    private SystemUserRoleAuthService systemUserRoleAuthService;

    @Override
    public int add(UCompanyUser uCompanyUser){
        return 0;
    }

    @Override
    public JsonResult addCompanyUser(UsersPhoneVo uPhoneVo) throws Exception {
        Map<String, String> userInfo = getWxUserInfo(uPhoneVo.getCode());
        int count = uCompanyUserMapper.selectByPhone(uPhoneVo.getPhone());
        if (count >= 1){
            return JsonResult.build("手机号已经注册过");
        }
        UCompanyUser uCompanyUser = new UCompanyUser();
        uCompanyUser.setVerificationCode(uPhoneVo.getVerificationCode());
        uCompanyUser.setCompanyId(uPhoneVo.getCompanyId());
        uCompanyUser.setCode(uPhoneVo.getCode());
        uCompanyUser.setPhone(uPhoneVo.getPhone());
        String string = EmojiParser.removeAllEmojis(uPhoneVo.getNickName());
        uCompanyUser.setNickname(string);
        uCompanyUser.setAvatarurl(uPhoneVo.getAvatarUrl());
        uCompanyUser.setOpenid(userInfo.get("openid"));
        uCompanyUser.setPassword(Md5Util.encoderByMd5(uPhoneVo.getPassword()));
        uCompanyUser.setCreatetime(new Date());
        int counts = uCompanyUserMapper.insertSelective(uCompanyUser);
        if(counts == 0){
            return JsonResult.build("注册失败");
        }
        return JsonResult.ok(uCompanyUser);
    }

    @Override
    public JsonResult verificationCode(UsersPhoneVo usersPhoneVo,Integer appid, String appkey){
        String msg = "";
        try {
            int count = uCompanyUserMapper.selectByPhone(usersPhoneVo.getPhone());
            if (count >= 1){
                return JsonResult.build("手机号已经注册过");
            }
            ThreadLocalRandom tlr = ThreadLocalRandom.current();
            Integer random = tlr.nextInt(1000,9999);
            SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
            SmsSingleSenderResult result = ssender.send(0, "86", usersPhoneVo.getPhone(),
                    "您的验证码是："+random+"，如非本人操作，请忽略本短信。", "", "");
            msg = result.errMsg;
            if(result.errMsg.equalsIgnoreCase("OK")){
                UCompanyUserCodeVo uCompanyUserCodeVo = new UCompanyUserCodeVo();
                uCompanyUserCodeVo.setCode(random.toString());
                uCompanyUserCodeVo.setPhone(usersPhoneVo.getPhone());
                return JsonResult.ok(uCompanyUserCodeVo);
            }
        } catch (HTTPException e) {
            // HTTP响应码错误
            e.printStackTrace();
        } catch (JSONException e) {
            // json解析错误
            e.printStackTrace();
        } catch (IOException e) {
            // 网络IO错误
            e.printStackTrace();
        }
        return JsonResult.build(msg);
    }

    @Override
    public JsonResult addUCompanyUserOpenid(UsersWxVo usersWxVo) {
        SystemLoginVo systemLoginVo = new SystemLoginVo();
        systemLoginVo.setLoginName(usersWxVo.getLoginName());
        systemLoginVo.setPassword(usersWxVo.getPassword());
        int id = systemUserRoleAuthService.systemUserLogin(systemLoginVo);
        if(id==0) {
            return JsonResult.build("登录失败");
        }

        UCompanyUser uCompanyUser = uCompanyUserMapper.selectById(id);
        uCompanyUser.setOpenid(usersWxVo.getOpenid());
        String string = EmojiParser.removeAllEmojis(usersWxVo.getNickname());
        uCompanyUser.setNickname(string);
        uCompanyUser.setAvatarurl(usersWxVo.getHeadimgurl());
        int updateUCompany = uCompanyUserMapper.updateByPrimaryKeySelective(uCompanyUser);
        UsersIdStatusVo usersIdStatusVo = new UsersIdStatusVo();
        usersIdStatusVo.setWxUserId(uCompanyUser.getCompanyId());
        usersIdStatusVo.setId(updateUCompany);
        usersIdStatusVo.setWxTowUserId(id);
        return JsonResult.ok(usersIdStatusVo);
    }

    /**
     * @param code 微信用户code
     * @author XOu
     * @description 获取微信用户信息
     * @version 1.0
     * @date 2018/7/1
     * @modified
     */
    public Map<String, String> getWxUserInfo(String code) {
        String openParam = "appid=" + WxConfigUtil.JKDL_BUSINESS_APPID + "&secret=" + WxConfigUtil.JKDL_BUSINESS_SECRT + "&js_code=" + code + "&grant_type=authorization_code";
        String openJsonStr = HttpUtil.SendGET("https://api.weixin.qq.com/sns/jscode2session", openParam);
        log.info("获取微信用户unionId接口返回参数{}", openJsonStr);

        Map openMap = JSON.parseObject(openJsonStr);
        if (openMap.containsKey("errcode")) {
            log.error("==========调用微信接口异常{}", String.valueOf(openMap.get("errmsg")));
            throw new BusinessException("调用微信接口异常");
        }
        log.info("获取的openid是", openMap.get("openid"));
        String sessionKey = String.valueOf(openMap.get("session_key"));
        String openid = String.valueOf(openMap.get("openid"));
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("sessionKey", sessionKey);
        resultMap.put("openid", openid);
        return resultMap;
    }

    @Override
    public JsonResult quitXcxUserLogin(UsersIdVo usersIdVo) {

        int updateUCompanyUser = uCompanyUserMapper.updateByXcxOpenid(usersIdVo);
        if(updateUCompanyUser == 0){
            return JsonResult.build("退出失败");
        }
        return JsonResult.ok(updateUCompanyUser);

    }

    @Override
    public JsonResult getCode(String phone, Integer appid, String appkey) {
        String msg = "";
        try {
            int count = uCompanyUserMapper.selectByPhone(phone);
            if (count == 0){
                return JsonResult.build("没有此手机号");
            }
            ThreadLocalRandom tlr = ThreadLocalRandom.current();
            Integer random = tlr.nextInt(1000,9999);
            SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
            SmsSingleSenderResult result = ssender.send(0, "86", phone,
                    "您的验证码是："+random+"，如非本人操作，请忽略本短信。", "", "");
            msg = result.errMsg;
            if(result.errMsg.equalsIgnoreCase("OK")){
                UCompanyUserCodeVo uCompanyUserCodeVo = new UCompanyUserCodeVo();
                uCompanyUserCodeVo.setCode(random.toString());
                uCompanyUserCodeVo.setPhone(phone);
                return JsonResult.ok(uCompanyUserCodeVo);
            }
        } catch (HTTPException e) {
            // HTTP响应码错误
            e.printStackTrace();
        } catch (JSONException e) {
            // json解析错误
            e.printStackTrace();
        } catch (IOException e) {
            // 网络IO错误
            e.printStackTrace();
        }

        return JsonResult.build(msg);

    }

    @Override
    public JsonResult updatePassword(UCompanyUserCodeVo CompanyUserCodeVo) throws Exception {
        SystemLoginVo systemLoginVo = new SystemLoginVo();
        systemLoginVo.setPassword(Md5Util.encoderByMd5(CompanyUserCodeVo.getCode()));
        systemLoginVo.setLoginName(CompanyUserCodeVo.getPhone());
        int count =  uCompanyUserMapper.updatePassword(systemLoginVo);
        if(count == 0){
            JsonResult.build("设置失败");
        }
        return JsonResult.ok(count);

    }
}
